package com.jstyle.jclife.adapter;

import android.animation.ValueAnimator;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.jstyle.blesdk.model.ExerciseMode;
import com.jstyle.jclife.R;
import com.jstyle.jclife.daoManager.GpsDataDaoManager;
import com.jstyle.jclife.daoManager.HeartDataDaoManager;
import com.jstyle.jclife.minterface.ItemDataClickListener;
import com.jstyle.jclife.minterface.OnScrollToListener;
import com.jstyle.jclife.model.GpsData;
import com.jstyle.jclife.model.HeartData;
import com.jstyle.jclife.model.ItemData;
import com.jstyle.jclife.model.PathRecord;
import com.jstyle.jclife.utils.CoordinateUtil;
import com.jstyle.jclife.utils.DateUtil;
import com.jstyle.jclife.utils.MapUtil;
import com.jstyle.jclife.utils.ResolveData;
import com.jstyle.jclife.utils.SchedulersTransformer;
import com.jstyle.jclife.utils.ScreenUtils;

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;


public class TrackRecordAdapter extends RecyclerView.Adapter<BaseViewHolder> {
    private String calLabel;
    private String heartLabel;
    private String durationLabel;
    private String stepLabel;
    private String hzLabel;
    private String distanceLabel;
    private String speedLabel;
    private String paceLabel;

    private String calUnit;
    private String heartUnit;
    private String durationUnit;
    private String stepUnit;
    private String hzUnit;
    private String distanceUnit;
    private String speedUnit;
    private String paceUnit;
    private Context mContext;
    private List<ItemData> mDataSet;
    private OnScrollToListener onScrollToListener;

    public void setOnScrollToListener(OnScrollToListener onScrollToListener) {
        this.onScrollToListener = onScrollToListener;
    }

    public TrackRecordAdapter(Context context) {
        mContext = context;
        heartLabel = mContext.getString(R.string.avg_hr_unit);
        heartUnit=mContext.getString(R.string.hr_laber);
        durationLabel = mContext.getString(R.string.Active_Minutes);
        stepLabel = mContext.getString(R.string.Step);
        stepUnit = mContext.getString(R.string.Steps_unit);

        paceLabel = mContext.getString(R.string.Average_pace_content);
        paceUnit = ResolveData.getPaceLabel(mContext);

        speedLabel = mContext.getString(R.string.Average_speed_content);
        speedUnit = ResolveData.getSpeedLabel(mContext);

        distanceLabel = mContext.getString(R.string.Distance);
        distanceUnit = ResolveData.getDistanceLabel(mContext);

        hzLabel = mContext.getString(R.string.Average_Stride);
        hzUnit=mContext.getString(R.string.Stride_label);

        calLabel = mContext.getString(R.string.cal_unit);
        calUnit=mContext.getString(R.string.cal_laber);
        mDataSet = new ArrayList<ItemData>();
    }

    @Override
    public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = null;
        switch (viewType) {
            case ItemData.ITEM_TYPE_PARENT:
                view = LayoutInflater.from(mContext).inflate(
                        R.layout.item_recycler_parent, parent, false);
                return new ParentViewHolder(view);
            case ItemData.ITEM_TYPE_RUN:
                view = LayoutInflater.from(mContext).inflate(
                        R.layout.item_history_exercise, parent, false);
                return new ExerciseRecordHistoryViewHolder(view);
            case ItemData.ITEM_TYPE_BIKING:
                view = LayoutInflater.from(mContext).inflate(
                        R.layout.item_exercisemode_bike, parent, false);
                return new ExerciseRecordBikingViewHolder(view);
            case ItemData.ITEM_TYPE_HIKING:
                view = LayoutInflater.from(mContext).inflate(
                        R.layout.item_exercisemode_hiking, parent, false);
                return new ExerciseRecordHikingViewHolder(view);
            case ItemData.ITEM_TYPE_OTHER:
                view = LayoutInflater.from(mContext).inflate(
                        R.layout.item_exercisemode_other, parent, false);
                return new ExerciseRecordOtherViewHolder(view);
            default:
                view = LayoutInflater.from(mContext).inflate(
                        R.layout.item_recycler_parent, parent, false);
                return new ParentViewHolder(view);
        }
    }

    @Override
    public void onBindViewHolder(BaseViewHolder holder, int position) {
        switch (getItemViewType(position)) {
            case ItemData.ITEM_TYPE_PARENT:
                ParentViewHolder imageViewHolder = (ParentViewHolder) holder;
                imageViewHolder.bindView(mDataSet.get(position), position,
                        imageClickListener);
                break;
            case ItemData.ITEM_TYPE_RUN:
                bindRun(holder, position);
                break;
            case ItemData.ITEM_TYPE_BIKING:
                bindBIKING(holder, position);
                break;
            case ItemData.ITEM_TYPE_HIKING:
                bindHiking(holder, position);
                break;
            case ItemData.ITEM_TYPE_OTHER:
                bindOther(holder, position);
                break;
            default:
                break;
        }
    }

    private ItemDataClickListener imageClickListener = new ItemDataClickListener() {

        @Override
        public void onExpandChildren(ItemData itemData) {
            int position = getCurrentPosition(itemData.getUuid());
            List<PathRecord> pathRecordList = itemData.getPathRecordList();
            List<ItemData> children = getChildrenByPath(pathRecordList, itemData.getTreeDepth());
            if (children == null) {
                return;
            }
            addAll(children, position + 1);// 插入到点击点的下方
            itemData.setChildren(children);
            if (onScrollToListener != null) {
                onScrollToListener.scrollTo(position);
            }
        }

        @Override
        public void onHideChildren(ItemData itemData) {
            int position = getCurrentPosition(itemData.getUuid());
            List<ItemData> children = itemData.getChildren();
            if (children == null) {
                return;
            }
            removeAll(position + 1, getChildrenCount(itemData) - 1);
            if (onScrollToListener != null) {
                onScrollToListener.scrollTo(position);
            }
            itemData.setChildren(null);
        }
    };

    @Override
    public int getItemCount() {
        return mDataSet.size();
    }

    private int getChildrenCount(ItemData item) {
        List<ItemData> list = new ArrayList<ItemData>();
        printChild(item, list);
        return list.size();
    }

    private void printChild(ItemData item, List<ItemData> list) {
        list.add(item);
        if (item.getChildren() != null) {
            for (int i = 0; i < item.getChildren().size(); i++) {
                printChild(item.getChildren().get(i), list);
            }
        }
    }


    public List<ItemData> getChildrenByPath(List<PathRecord> pathRecordList, int treeDepth) {
        treeDepth++;
        List<ItemData> list = new ArrayList<ItemData>();
        for (PathRecord pathRecord : pathRecordList) {
            ItemData itemData = new ItemData(getExerciseMode(pathRecord), "", "", UUID
                    .randomUUID().toString(), treeDepth, null);
            itemData.setPathRecord(pathRecord);
            list.add(itemData);
        }
        return list;
    }

    private int getExerciseMode(PathRecord pathRecord) {
        int mode = pathRecord.getExerciseMode();
        int viewType = 0;
        switch (mode) {
            case ExerciseMode.Mode_RUN:
                viewType = ItemData.ITEM_TYPE_RUN;
                break;
            case ExerciseMode.Mode_CYCLING:
                viewType = ItemData.ITEM_TYPE_BIKING;
                break;
            case ExerciseMode.Mode_CLIMB:
                viewType = ItemData.ITEM_TYPE_HIKING;
                break;
            default:
                viewType = ItemData.ITEM_TYPE_OTHER;
                break;
        }
        return viewType;
    }

    /**
     * 从position开始删除，删除
     *
     * @param position
     * @param itemCount 删除的数目
     */
    protected void removeAll(int position, int itemCount) {
        for (int i = 0; i < itemCount; i++) {
            mDataSet.remove(position);
        }
        notifyItemRangeRemoved(position, itemCount);
    }

    protected int getCurrentPosition(String uuid) {
        for (int i = 0; i < mDataSet.size(); i++) {
            if (uuid.equalsIgnoreCase(mDataSet.get(i).getUuid())) {
                return i;
            }
        }
        return -1;
    }

    @Override
    public int getItemViewType(int position) {
        return mDataSet.get(position).getType();
    }

    public void add(ItemData text, int position) {
        mDataSet.add(position, text);
        notifyItemInserted(position);
    }

    public void addAll(List<ItemData> list, int position) {
        mDataSet.addAll(position, list);
        notifyItemRangeInserted(position, list.size());
    }

    public void delete(int pos) {
        if (pos >= 0 && pos < mDataSet.size()) {
            if (mDataSet.get(pos).getType() == ItemData.ITEM_TYPE_PARENT
                    && mDataSet.get(pos).isExpand()) {// 父组件并且子节点已经展开
                for (int i = 0; i < mDataSet.get(pos).getChildren().size() + 1; i++) {
                    mDataSet.remove(pos);
                }
                notifyItemRangeRemoved(pos, mDataSet.get(pos).getChildren()
                        .size() + 1);
            } else {// 孩子节点，或没有展开的父节点
                mDataSet.remove(pos);
                notifyItemRemoved(pos);
            }
        }
    }

    public static class ParentViewHolder extends BaseViewHolder {
        public TextView textMonthDate;
        public TextView textTotalTime;
        public TextView textBikeDistance;
        public TextView textRunDistance;
        public ImageView expand;
        public ConstraintLayout relativeLayout;
        private int itemMargin;

        public ParentViewHolder(View itemView) {
            super(itemView);
            expand = (ImageView) itemView.findViewById(R.id.expand);
            textMonthDate = (TextView) itemView.findViewById(R.id.tv_record_parent_time);
            textTotalTime = (TextView) itemView.findViewById(R.id.tv_month_time);
            textRunDistance  = (TextView) itemView.findViewById(R.id.tv_run_value);
            textBikeDistance = (TextView) itemView.findViewById(R.id.tv_bike_value);
            relativeLayout = (ConstraintLayout) itemView.findViewById(R.id.container);
            itemMargin = itemView.getContext().getResources()
                    .getDimensionPixelSize(R.dimen.item_margin);
        }

        public void bindView(final ItemData itemData, final int position,
                             final ItemDataClickListener imageClickListener) {
            ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) expand
                    .getLayoutParams();
            params.leftMargin = itemMargin * itemData.getTreeDepth();
            expand.setLayoutParams(params);
            Context context = itemView.getContext();
            textMonthDate.setText(DateUtil.getShowRecodeDate(context, itemData.getmDate()));
            List<PathRecord> pathRecords = itemData.getPathRecordList();
            int totalTime = 0;
            float distanceRun=0;
            float distanceBike=0;

            for (PathRecord pathRecord : pathRecords) {
                totalTime += Integer.valueOf(pathRecord.getMDuration());
                int mode=pathRecord.getExerciseMode();
                float distance=Float.valueOf(pathRecord.getMDistance());
                if(mode== ExerciseMode.Mode_RUN){
                    distanceRun=add(distanceRun,distance);
                }else if(mode== ExerciseMode.Mode_CYCLING){
                    distanceBike+=distance;
                }
            }
            textTotalTime.setText(DateUtil.getExerciseListTotalTime(totalTime));
            textRunDistance.setText(String.valueOf(distanceRun));
            textBikeDistance.setText(String.valueOf(distanceBike));
            if (itemData.isExpand()) {
                expand.setRotation(180);
                List<ItemData> children = itemData.getChildren();
            } else {
                expand.setRotation(0);
            }
            relativeLayout.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (imageClickListener != null) {
                        if (itemData.isExpand()) {
                            imageClickListener.onHideChildren(itemData);
                            itemData.setExpand(false);
                            rotationExpandIcon(180, 0);
                        } else {
                            imageClickListener.onExpandChildren(itemData);
                            itemData.setExpand(true);
                            rotationExpandIcon(0, 180);
                            List<ItemData> children = itemData.getChildren();
                        }
                    }

                }
            });

        }
        public  float add(float v1, float v2) {

            BigDecimal b1 = new BigDecimal(Float.toString(v1));
            BigDecimal b2 = new BigDecimal(Float.toString(v2));
            return b1.add(b2).floatValue();
        }

        @TargetApi(Build.VERSION_CODES.HONEYCOMB)
        private void rotationExpandIcon(float from, float to) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                ValueAnimator valueAnimator = ValueAnimator.ofFloat(from, to);
                valueAnimator.setDuration(150);
                valueAnimator.setInterpolator(new DecelerateInterpolator());
                valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

                    @Override
                    public void onAnimationUpdate(ValueAnimator valueAnimator) {
                        expand.setRotation((Float) valueAnimator.getAnimatedValue());
                    }
                });
                valueAnimator.start();
            }
        }
    }
    private Spannable getSpannable(String text, String label) {
        int start = text.indexOf(label);
        int end = start + label.length();
        Spannable kcalSpannable = new SpannableString(text);
        setColorSpannable(kcalSpannable, start, end, Color.parseColor("#86878C"));
        return kcalSpannable;
    }

    private void setColorSpannable(Spannable word, int start, int end, int textColor) {
        word.setSpan(new ForegroundColorSpan(textColor), start, end, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
    }

    private void initGpsData(final Button buttonHeart, final Button btSpeed, final Button btDistance, final Button mapTrack,
                             final BaseViewHolder holder, final PathRecord pathRecord) {
        final List<LatLng> mOriginLatLngList = new ArrayList<>();
        final List<HeartData> mHeartDataList = new ArrayList<>();
        Log.i(TAG, "initGpsData: "+pathRecord.getMDate());
        final int time = Integer.valueOf(pathRecord.getMDuration());
        Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> e) throws Exception {
                String time = pathRecord.getMDate();
                String duration = pathRecord.getMDuration();
                long startL = DateUtil.getGpsDateLong(time);
                long endL = startL + Integer.valueOf(duration) * 1000;
                String endTime = DateUtil.getFormatTimeString(endL);
                List<GpsData> gpsDataList = GpsDataDaoManager.getPathRecord(time, endTime);
                mHeartDataList.addAll(HeartDataDaoManager.queryGpsData(time, endTime));
                if (gpsDataList != null && gpsDataList.size() != 0) {
                    GpsData gpsData = gpsDataList.get(0);
                    if(!TextUtils.isEmpty(gpsData.getPathLineString())){
                        Log.i(TAG, "subscribe: "+time+" "+gpsData.getPathLineString());
                        List<AMapLocation>aMapLocationList= MapUtil.parseLocations(gpsData.getPathLineString());
                        mOriginLatLngList.addAll(MapUtil.parseLatLngList(aMapLocationList));
                    }else{
                        String[] LatitudeStringArray = gpsData.getLatitudeString().split(",");
                        String[] LongitudeStringArray = gpsData.getLongitudeString().split(",");
                        for (int i = 0; i < LatitudeStringArray.length; i++) {
                            LatLng latLng = CoordinateUtil.transformFromWGSToGCJ(
                                    new LatLng(Double.valueOf(LatitudeStringArray[i]), Double.valueOf(LongitudeStringArray[i])));
                            mOriginLatLngList.add(latLng);
                        }
                        Log.i(TAG, "subscribe: "+mOriginLatLngList.size());
                    }


                }

                e.onComplete();
            }
        }).compose(SchedulersTransformer.<Integer>applySchedulers()).subscribe(new Observer<Integer>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Integer value) {

            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                Log.i(TAG, "onError: " + e.getMessage());
            }

            @Override
            public void onComplete() {
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (clickListener != null)
                            clickListener.onClick(pathRecord, mOriginLatLngList.size() == 0 ? null : mOriginLatLngList.get(0));
                    }
                });
                String heartString = initAvgHeart(mHeartDataList) + " "+heartUnit+"\n" + heartLabel;
                buttonHeart.setText(getSpannable(heartString, heartLabel));
                float distance = Float.valueOf(pathRecord.getMDistance());
                String showDistance = ResolveData.getShowDistance(String.valueOf(distance));
                float speed = Float.valueOf(showDistance) * 3600f / time;
                NumberFormat numberFormat = NumberFormat.getNumberInstance();
                numberFormat.setMaximumFractionDigits(2);
                String speedString = numberFormat.format(speed) +" "+speedUnit+ "\n" + speedLabel;
                String distanceString = showDistance +" "+ distanceUnit+"\n" + distanceLabel;
                btSpeed.setText(getSpannable(speedString, speedLabel));
                btDistance.setText(getSpannable(distanceString, distanceLabel));
                Drawable drawableRight = holder.itemView.getContext().getResources().getDrawable(R.drawable.map_right);
                drawableRight.setBounds(0, 0, drawableRight.getMinimumWidth(), drawableRight.getMinimumHeight());
                mapTrack.setCompoundDrawables(null, null, mOriginLatLngList.size() == 0 ? null : drawableRight, null);
            }
        });


    }

    private int initAvgHeart(List<HeartData> heartDataList) {
        int avgHeart = 0;
        int count = 0;
        float totalHeartRate = 0;
        for (int i = 0; i < heartDataList.size(); i++) {
            float heartRate = heartDataList.get(i).getHeart();
            if (heartRate != 0) count++;
            totalHeartRate += heartRate;
        }
        avgHeart = count == 0 ? 0 : (int) Math.rint(totalHeartRate / count);
        return avgHeart;
    }



    private LatLngBounds getBounds(List<LatLng> latLngs) {
        LatLngBounds.Builder b = LatLngBounds.builder();
        if (latLngs == null) {
            return b.build();
        }
        for (int i = 0; i < latLngs.size(); i++) {
            b.include(latLngs.get(i));
        }
        return b.build();

    }

    onMapItemClickListener clickListener;

    public interface onMapItemClickListener {
        public void onClick(PathRecord pathRecord, LatLng latLng);
    }

    public void setMapClickListener(onMapItemClickListener clickListener) {
        this.clickListener = clickListener;
    }

    private void bindOther(BaseViewHolder holder, int position) {
        ExerciseRecordOtherViewHolder viewHolder = (ExerciseRecordOtherViewHolder) holder;
        final PathRecord pathRecord = mDataSet.get(position).getPathRecord();
        int mode = pathRecord.getExerciseMode();
        String heart = pathRecord.getHeart();
        Context context = viewHolder.itemView.getContext();
        NumberFormat numberFormat = NumberFormat.getNumberInstance();
        numberFormat.setMaximumFractionDigits(2);
        numberFormat.setMinimumFractionDigits(2);
        String[] modeArray = context.getResources().getStringArray(R.array.mode_name);
        if (mode > 10) mode = 10;
        int drawableId = context.getResources().
                getIdentifier("history_mode_" + mode, "drawable", context.getPackageName());
        viewHolder.imageViewExerciseMode.setImageResource(drawableId);
        ScreenUtils.setTitleTypeface(viewHolder.buttonExerciseMode);
        viewHolder.buttonExerciseMode.setText(modeArray[mode]);
        String date = pathRecord.getMDate();
        String[] dateArray = date.split(" ");
        viewHolder.textViewExerciseDate.setText(DateUtil.getShowRecodeTime(context, dateArray[0]) + "  " + dateArray[1]);
        String duration = DateUtil.getSportTime(Integer.parseInt(pathRecord.getMDuration())) + "\n" + durationLabel;
        String cal = pathRecord.getCalString() + " "+calUnit+"\n" + calLabel;
        String heartString = heart +  " "+heartUnit+"\n" + heartLabel;
        viewHolder.buttonExerciseCal.setText(getSpannable(cal, calLabel));
        viewHolder.buttonExerciseDurtuion.setText(getSpannable(duration, durationLabel));
        viewHolder.buttonHeart.setText(getSpannable(heartString, heartLabel));
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (clickListener != null) clickListener.onClick(pathRecord, null);
            }
        });
    }

    private void bindHiking(BaseViewHolder holder, int position) {
        ExerciseRecordHikingViewHolder viewHolder = (ExerciseRecordHikingViewHolder) holder;
        PathRecord pathRecord = mDataSet.get(position).getPathRecord();
        int mode = pathRecord.getExerciseMode();
        String heart = pathRecord.getHeart();
        Context context = viewHolder.itemView.getContext();
        NumberFormat numberFormat = NumberFormat.getNumberInstance();
        numberFormat.setMaximumFractionDigits(2);
        String[] modeArray = context.getResources().getStringArray(R.array.mode_name);
        String showDistance = pathRecord.getMDistance();
        int drawableId = context.getResources().
                getIdentifier("history_mode_" + mode, "drawable", context.getPackageName());
        viewHolder.imageViewExerciseMode.setImageResource(drawableId);
        viewHolder.buttonExerciseMode.setText(modeArray[mode]);
        String date = pathRecord.getMDate();
        String[] dateArray = date.split(" ");
        viewHolder.textViewExerciseDate.setText(DateUtil.getShowRecodeTime(context, dateArray[0]) + "  " + dateArray[1]);
        ScreenUtils.setTitleTypeface(viewHolder.buttonExerciseMode);
        String cal = pathRecord.getCalString() + " "+calUnit+"\n" + calLabel;
        String duration = DateUtil.getSportTime(Integer.parseInt(pathRecord.getMDuration())) + "\n" + durationLabel;
        String distanceString = showDistance + "\n" + distanceLabel;
        String step = pathRecord.getMStep() + " "+stepUnit+"\n" + stepLabel;
        viewHolder.buttonExerciseStep.setText(getSpannable(step, stepLabel));
        viewHolder.buttonExerciseCal.setText(getSpannable(cal, calLabel));
        viewHolder.buttonExerciseDurtuion.setText(getSpannable(duration, durationLabel));
        viewHolder.buttonExerciseDistance.setText(getSpannable(distanceString, distanceLabel));
        initGpsData(viewHolder.buttonHeart, viewHolder.buttonExerciseSpeed,
                viewHolder.buttonExerciseDistance, viewHolder.buttonExerciseMode, holder, pathRecord);

    }

    private void bindBIKING(BaseViewHolder holder, int position) {
        NumberFormat numberFormat = NumberFormat.getNumberInstance();
        numberFormat.setMaximumFractionDigits(2);
        ExerciseRecordBikingViewHolder viewHolder = (ExerciseRecordBikingViewHolder) holder;
        PathRecord pathRecord = mDataSet.get(position).getPathRecord();
        String heart = pathRecord.getHeart();
        int mode = pathRecord.getExerciseMode();
        Context context = viewHolder.itemView.getContext();
        String[] modeArray = context.getResources().getStringArray(R.array.mode_name);
        String showDistance = null;
        try {
            showDistance = numberFormat.parse(pathRecord.getMDistance()).toString();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int drawableId = context.getResources().
                getIdentifier("history_mode_" + mode, "drawable", context.getPackageName());
        viewHolder.imageViewExerciseMode.setImageResource(drawableId);
        viewHolder.buttonExerciseMode.setText(modeArray[mode]);
        String date = pathRecord.getMDate();
        String[] dateArray = date.split(" ");
        viewHolder.textViewExerciseDate.setText(DateUtil.getShowRecodeTime(context, dateArray[0]) + "  " + dateArray[1]);
        String cal = pathRecord.getCalString() + " "+calUnit+"\n" + calLabel;
        String duration = DateUtil.getSportTime(Integer.parseInt(pathRecord.getMDuration())) + "\n" + durationLabel;
        String distanceString = showDistance + "\n" + distanceLabel;
        ScreenUtils.setTitleTypeface(viewHolder.buttonExerciseMode);
        viewHolder.buttonExerciseCal.setText(getSpannable(cal, calLabel));
        viewHolder.buttonExerciseDurtuion.setText(getSpannable(duration, durationLabel));

        viewHolder.buttonExerciseDistance.setText(getSpannable(distanceString, distanceLabel));
        // viewHolder.buttonExerciseSpeed.setText(getSpannable(speedString, speedLabel));
        initGpsData(viewHolder.buttonHeart, viewHolder.buttonExerciseSpeed, viewHolder.buttonExerciseDistance, viewHolder.buttonExerciseMode, holder, pathRecord);
    }

    private void bindRun(BaseViewHolder holder, int position) {
        NumberFormat numberFormat = NumberFormat.getNumberInstance();
        numberFormat.setMaximumFractionDigits(2);
        ExerciseRecordHistoryViewHolder viewHolder = (ExerciseRecordHistoryViewHolder) holder;
        PathRecord pathRecord = mDataSet.get(position).getPathRecord();
        int mode = pathRecord.getExerciseMode();
        String heart = pathRecord.getHeart();
        Context context = viewHolder.itemView.getContext();
        String[] modeArray = context.getResources().getStringArray(R.array.mode_name);
        int drawableId = context.getResources().
                getIdentifier("history_mode_" + mode, "drawable", context.getPackageName());
        ScreenUtils.setTitleTypeface(viewHolder.buttonExerciseMode);
        String date = pathRecord.getMDate();
        String[] dateArray = date.split(" ");
        String cal = pathRecord.getCalString() +" "+calUnit+ "\n" + calLabel;

        String pace = ResolveData.getShowPace(mContext, pathRecord.getMAveragespeed()) + " "+paceUnit+"\n" + paceLabel;
        int time = Integer.valueOf(pathRecord.getMDuration());
        String step = pathRecord.getMStep();
        int stepM = (int) Math.rint(Double.valueOf(step) * 60 / time);
        String duration = DateUtil.getSportTime(time) + "\n" + durationLabel;
        String stepHz = stepM + " "+hzUnit+"\n" + hzLabel;
        String stepString = step +" "+ stepUnit+ "\n" + stepLabel;
        viewHolder.buttonExerciseStep.setText(getSpannable(stepString, stepLabel));
        viewHolder.buttonExerciseCal.setText(getSpannable(cal, calLabel));
        viewHolder.buttonExerciseDurtuion.setText(getSpannable(duration, durationLabel));
        viewHolder.imageViewExerciseMode.setImageResource(drawableId);
        viewHolder.buttonExerciseMode.setText(modeArray[mode]);
        viewHolder.textViewExerciseDate.setText(DateUtil.getShowRecodeTime(context, dateArray[0]) + "  " + dateArray[1]);
        viewHolder.buttonExerciseSpace.setText(getSpannable(pace, paceLabel));
        viewHolder.buttonExerciseStephz.setText(getSpannable(stepHz, hzLabel));
        initGpsData(viewHolder.buttonHeart, viewHolder.buttonExerciseSpeed, viewHolder.buttonExerciseDistance, viewHolder.buttonExerciseMode, viewHolder, pathRecord);
    }

    private static final String TAG = "ExerciseRecordHistoryAd";


    public class ExerciseRecordHistoryViewHolder extends BaseViewHolder {//跑步
        @BindView(R.id.imageView_exercise_mode)
        ImageView imageViewExerciseMode;
        @BindView(R.id.button_exercise_mode)
        Button buttonExerciseMode;
        @BindView(R.id.textView_exercise_date)
        TextView textViewExerciseDate;

        @BindView(R.id.button_exercise_durtuion)
        Button buttonExerciseDurtuion;
        @BindView(R.id.button_exercise_cal)
        Button buttonExerciseCal;
        @BindView(R.id.button_exercise_distance)
        Button buttonExerciseDistance;
        @BindView(R.id.button_exercise_speed)
        Button buttonExerciseSpeed;
        @BindView(R.id.button_exercise_space)
        Button buttonExerciseSpace;
        @BindView(R.id.button_exercise_step)
        Button buttonExerciseStep;
        @BindView(R.id.button_exercise_stephz)
        Button buttonExerciseStephz;
        @BindView(R.id.button_heart)
        Button buttonHeart;

        public ExerciseRecordHistoryViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    public class ExerciseRecordOtherViewHolder extends BaseViewHolder {//其他剩下的
        @BindView(R.id.imageView_exercise_mode)
        ImageView imageViewExerciseMode;
        @BindView(R.id.button_exercise_mode)
        Button buttonExerciseMode;
        @BindView(R.id.textView_exercise_date)
        TextView textViewExerciseDate;
        @BindView(R.id.button_exercise_durtuion)
        Button buttonExerciseDurtuion;
        @BindView(R.id.button_exercise_cal)
        Button buttonExerciseCal;
        @BindView(R.id.button_heart)
        Button buttonHeart;

        public ExerciseRecordOtherViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    public class ExerciseRecordHikingViewHolder extends BaseViewHolder {
        @BindView(R.id.imageView_exercise_mode)
        ImageView imageViewExerciseMode;
        @BindView(R.id.button_exercise_mode)
        Button buttonExerciseMode;
        @BindView(R.id.textView_exercise_date)
        TextView textViewExerciseDate;

        @BindView(R.id.button_exercise_durtuion)
        Button buttonExerciseDurtuion;
        @BindView(R.id.button_exercise_cal)
        Button buttonExerciseCal;
        @BindView(R.id.button_exercise_distance)
        Button buttonExerciseDistance;
        @BindView(R.id.button_exercise_speed)
        Button buttonExerciseSpeed;
        @BindView(R.id.button_exercise_step)
        Button buttonExerciseStep;
        @BindView(R.id.button_heart)
        Button buttonHeart;

        public ExerciseRecordHikingViewHolder(View itemView) {//远足
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    public class ExerciseRecordBikingViewHolder extends BaseViewHolder {//骑车
        @BindView(R.id.imageView_exercise_mode)
        ImageView imageViewExerciseMode;
        @BindView(R.id.button_exercise_mode)
        Button buttonExerciseMode;
        @BindView(R.id.textView_exercise_date)
        TextView textViewExerciseDate;

        @BindView(R.id.button_exercise_durtuion)
        Button buttonExerciseDurtuion;
        @BindView(R.id.button_exercise_cal)
        Button buttonExerciseCal;
        @BindView(R.id.button_exercise_distance)
        Button buttonExerciseDistance;
        @BindView(R.id.button_exercise_speed)
        Button buttonExerciseSpeed;
        @BindView(R.id.button_heart)
        Button buttonHeart;

        public ExerciseRecordBikingViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    private float getDistance(List<LatLng> list) {
        float distance = 0;
        if (list == null || list.size() == 0) {
            return distance;
        }
        for (int i = 0; i < list.size() - 1; i++) {
            LatLng firstLatLng = list.get(i);
            LatLng secondLatLng = list.get(i + 1);
            double betweenDis = AMapUtils.calculateLineDistance(firstLatLng,
                    secondLatLng);
            distance = (float) (distance + betweenDis);
        }

        return distance / 1000f;
    }

}
